package edu.uestc.canary.admin.web.interceptor;

import com.alibaba.fastjson2.JSONObject;
import edu.uestc.canary.admin.commons.AdministratorHolder;
import edu.uestc.canary.entity.pojo.Administrator;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Enumeration;

/**
 * 登录校验拦截器
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Resource private StringRedisTemplate stringTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //处理预请求的代码
        if (request.getMethod().equals("OPTIONS")) {
            return true;
        }
        var token = request.getHeader("Authorization");

        if(!StringUtils.hasLength(token)){ //未登录认证
            response.setStatus(401); //未登录认证响应状态码
            return false;
        }
        var value = stringTemplate.opsForValue().get("canary:token:" + token);
        if(!StringUtils.hasLength(value)){ //value不存在===登录用户不存在
            response.setStatus(401); //未登录认证响应状态码
            return false;
        }
        var administrator = JSONObject.parseObject(value, Administrator.class);
        AdministratorHolder.set(administrator);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        AdministratorHolder.remove();
    }
}
